package com.guomei.controller.curse;

import com.guomei.bean.curse.AddOrUpdateCourse;
import com.guomei.bean.curse.CountByCourseAndUserIdDTO;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.CoursePurchaseCheckRequest;
import com.guomei.bean.curse.dto.DistributorCourseListDTO;
import com.guomei.constans.CourseCode;
import com.guomei.service.curse.CourseService;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 课程控制器
 */
@RestController
@RequestMapping("/api1/course")
@Slf4j
public class CourseController {
    @Autowired
    private CourseService courseService;
    /**
     * 获取课程信息（包含教师信息）
     * @return 课程列表
     */
    @PostMapping("/select")
    public Result<?> getAllCourses(@RequestBody Course  course, HttpServletRequest request) {
        log.info("获取课程信息（包含教师信息）入参->{}", course);
        try {
            if (course == null || course.getPageNum() == null || course.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (course.getPageNum() <= 0 || course.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            return courseService.getByConditionWithTeacher(course,request);
        } catch (Exception e) {
            log.info("获取课程信息失败",e);
            return Result.fail("获取课程信息失败");
        }
    }

    /**
     * 根据用户id和课程id统计数据
     */
    @PostMapping("/CountByCourseAndUserId")
    public Result<?> CountByCourseAndUserId(@Valid @RequestBody CountByCourseAndUserIdDTO countByCourseAndUserIdDTO, BindingResult result) {
        log.info("根据用户id和课程id统计数据入参：{}", countByCourseAndUserIdDTO);
        //实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            return courseService.CountByCourseAndUserId(countByCourseAndUserIdDTO);
        } catch (Exception e) {
            log.info("根据用户id和课程id统计数据失败",e);
            return Result.fail("根据用户id和课程id统计数据失败");
        }
    }


    /**
     * 创建/修改新课程
     * @param addOrUpdateCourse 课程信息
     * @return 创建/修改新课程
     */
    @PostMapping("/addCourse")
    public Result<?> createCourse(@Valid @RequestBody AddOrUpdateCourse addOrUpdateCourse, BindingResult result) {
        log.info("创建/修改课程入参：{}", addOrUpdateCourse);
        //实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        Course course = new Course();
        course.setCourseName(addOrUpdateCourse.getCourseName());
        course.setCoverImage(addOrUpdateCourse.getCoverImage());
        course.setBannerImage(addOrUpdateCourse.getBannerImage());
        course.setDescription(addOrUpdateCourse.getDescription());
        course.setTeacherId(addOrUpdateCourse.getTeacherId());
        course.setPrice(addOrUpdateCourse.getPrice());
        course.setSalePrice(addOrUpdateCourse.getSalePrice());
        course.setDuration(addOrUpdateCourse.getDuration());
        course.setDiscountEndTime(addOrUpdateCourse.getDiscountEndTime());
        course.setCourseType(addOrUpdateCourse.getCourseType());
        course.setCanTry(addOrUpdateCourse.getCanTry());
        course.setTryDuration(addOrUpdateCourse.getTryDuration());
        course.setDistributionRatio(addOrUpdateCourse.getDistributionRatio());
        course.setSuitablePeople(addOrUpdateCourse.getSuitablePeople());
        course.setLearningProcess(addOrUpdateCourse.getLearningProcess());
        course.setFaq(addOrUpdateCourse.getFaq());
        course.setScore(addOrUpdateCourse.getScore());
        course.setStudentCount(addOrUpdateCourse.getStudentCount());
        course.setShareTitle(addOrUpdateCourse.getShareTitle());
        course.setShareDescription(addOrUpdateCourse.getShareDescription());
        course.setShareImage(addOrUpdateCourse.getShareImage());
        course.setCreatedTime(addOrUpdateCourse.getCreatedTime());
        course.setUpdatedTime(addOrUpdateCourse.getUpdatedTime());
        course.setDistributionUserId(addOrUpdateCourse.getDistributionUserId());
        course.setOpenUrl(addOrUpdateCourse.getOpenUrl());
        course.setApproveId(addOrUpdateCourse.getApproveId());
        course.setCourseMirrorUrl(addOrUpdateCourse.getCourseMirrorUrl());
        course.setTryVideoUrl(addOrUpdateCourse.getTryVideoUrl());
        course.setCategoryId(addOrUpdateCourse.getCategoryId());
        course.setCourseMirrorImg(addOrUpdateCourse.getCourseMirrorImg());
        course.setDistributionType(addOrUpdateCourse.getDistributionType());

        try {
            if (addOrUpdateCourse.getId() == null){
                log.info("进行创建课程处理");
                course.setStatus((short) CourseCode.DRAFT.getCode());
                return courseService.save(course);
            }else {
                log.info("进行修改课程处理");
                course.setStatus(addOrUpdateCourse.getStatus());
                course.setId(addOrUpdateCourse.getId());
                course.setEditType(addOrUpdateCourse.getEditType());
                return courseService.update(course);
            }
        } catch (Exception e) {
            log.info("创建/修改课程处理失败", e);
            return Result.error("处理失败");
        }
    }


    @PostMapping("/detail")
    public Result<?> getCourseDetail(@RequestBody Map<String, Object> requestBody, HttpServletRequest request) {
        Object courseIdObj = requestBody.get("courseId");
        if (courseIdObj == null) {
            return Result.fail("courseId参数不能为空");
        }
        Long courseId;
        try {
            if (courseIdObj instanceof Number) {
                courseId = ((Number) courseIdObj).longValue();
            } else {
                courseId = Long.parseLong(courseIdObj.toString());
            }
            log.info("获取课程详情入参：{}", courseId);
            return courseService.getCourseDetail(courseId, request);
        } catch (Exception e) {
            log.error("获取课程详情失败", e);
            return Result.fail("获取课程详情失败");
        }
    }

    /**
     * 获取用户课程学习统计信息
     * @param requestBody 请求参数，包含userId
     * @return 包含学习统计信息的用户信息
     */
    @PostMapping("/learnStats")
    public Result<?> getCourseLearnStats(@RequestBody Map<String, Object> requestBody) {
        log.info("获取用户课程学习统计信息入参：{}", requestBody);
        
        Object userIdObj = requestBody.get("userId");
        if (userIdObj == null) {
            return Result.fail("userId参数不能为空");
        }
        
        Long userId;
        try {
            if (userIdObj instanceof Number) {
                userId = ((Number) userIdObj).longValue();
            } else {
                userId = Long.parseLong(userIdObj.toString());
            }
            
            return courseService.getCourseLearnStats(userId);
        } catch (NumberFormatException e) {
            log.error("userId参数格式错误: {}", userIdObj, e);
            return Result.fail("userId参数格式错误");
        } catch (Exception e) {
            log.error("获取用户课程学习统计信息失败", e);
            return Result.fail("获取学习统计信息失败");
        }
    }

    @PostMapping("/deleteCourse")
    public Result<?> deleteCourse(@RequestBody Course  course) {
        log.info("删除课程入参：{}", course);
        if (course.getId() == null){
            return Result.fail("id参数不能为空");
        }
        return courseService.removeById(course.getId()) ? Result.success("处理成功") : Result.fail("处理失败");
    };

    @PostMapping("selectDistributionList")
    public Result<?> selectDistributionList(@RequestBody Course  course) {
        log.info("查分销人员/审批老师列表信息入参->{}", course);
        try {
            if (course == null || course.getPageNum() == null || course.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (course.getPageNum() <= 0 || course.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            if (course.getId() == null) {
                return Result.fail("课程id不能为空");
            }
            if (course.getTeacherType() == null){
                course.setTeacherType("老师类型不能为空");
            }
            return courseService.selectDistributionList(course);
        } catch (Exception e) {
            log.info("查询分销人员/审批老师列表信息失败",e);
            return Result.fail("查询分销人员/审批老师列表信息");
        }
    }



    @GetMapping("/dataPanel")
    public Result<?> getDataPanel() {
        return courseService.getDataPanel();
    }

    /**
     * 分页查询课程列表及统计信息（管理端）
     * 包含：课程基本信息、分销老师数量、订单数量、销售金额、分销金额
     * @param queryDTO 查询条件（包含分页参数、课程名称、状态、类型等）
     * @return 课程统计列表
     */
    @PostMapping("/courseListWithStats")
    public Result<?> getCourseListWithStats(@RequestBody com.guomei.bean.curse.dto.CourseStatsQueryDTO queryDTO) {
        log.info("分页查询课程统计列表入参：{}", queryDTO);
        
        try {
            return courseService.getCourseListWithStats(queryDTO);
        } catch (Exception e) {
            log.error("查询课程统计列表失败", e);
            return Result.fail("查询课程统计列表失败");
        }
    }


    /**
     * 查询分销课程列表
     * 查询所有符合条件的课程，如果课程有该teacherId的分销关系则一起返回，没有则courseDistributerRel为null
     * @param dto 查询条件（包含必传的teacherId用于过滤分销关系、分页参数、可选的课程名称/状态/类型等）
     * @return 分销课程列表（CourseDistribute分页结果）
     */
    @PostMapping("/distributorCourseList")
    public Result<?> getDistributorCourseList(@Valid @RequestBody DistributorCourseListDTO dto, BindingResult result) {
        log.info("查询分销课程列表入参：{}", dto);
        
        // 实体类注解参数校验
        Result<?> validationResult = ValidationUtil.validInputParams(result);
        if (validationResult != null) {
            return validationResult;
        }
        
        try {
            return courseService.getDistributorCourseList(dto);
        } catch (Exception e) {
            log.error("查询分销课程列表失败", e);
            return Result.fail("查询分销课程列表失败");
        }
    }


    // 注意：buyCourse 方法需要根据实际业务需求实现
    
    /**
     * 检查用户是否购买了指定课程列表
     * @param request 包含courseIds和userId的请求对象
     * @return 返回与courseIds对应的购买状态数组
     */
    @PostMapping("/checkPurchaseStatus")
    public Result<?> checkPurchaseStatus(@RequestBody CoursePurchaseCheckRequest request) {
        log.info("检查课程购买状态入参：{}", request);
        try {
            if (request.getCourseIds() == null || request.getCourseIds().isEmpty()) {
                return Result.fail("课程ID列表不能为空");
            }
            if (request.getUserId() == null) {
                return Result.fail("用户ID不能为空");
            }
            
            List<Boolean> purchaseStatus = courseService.checkCoursePurchaseStatus(request.getUserId(), request.getCourseIds());
            return Result.success("查询成功", purchaseStatus);
        } catch (Exception e) {
            log.error("检查课程购买状态失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
}
